﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RXY_Mall.Application.SystemSetting.Dto;
using RXY_Mall.Core;
using RXY_Mall.Domain;
using System.Data.Entity;

namespace RXY_Mall.Application.SystemSetting
{
    public class SystemSettingService : RXY_MallAppServiceBase, ISystemSettingService
    {
        #region 商品服务
        public async Task<Response<bool>> AddorEditService(int managerId, ServiceInput input)
        {
            //TODO:数据验证
            StringBuilder errorList = new StringBuilder();
            if (string.IsNullOrEmpty(input.title))
            {
                errorList.Append("服务名称不能为空；</br>");
            }
            if (!string.IsNullOrWhiteSpace(errorList.ToString()))
            {
                return ReturnError<bool>(errorList.ToString());
            }
            if (input.id > 0)
            {
                var entity = db.gw_goods_services.FirstOrDefault(i => i.id == input.id);
                if (entity != null)
                {
                    entity.title = input.title;
                    entity.content = input.content == null ? "" : input.content;
                    entity.remark = input.remark == null ? "" : input.remark;
                    entity.sort = input.sort;
                    var result = await db.SaveChangesAsync();
                    return ReturnSuccess<bool>(true);
                }
                return ReturnError<bool>("服务信息不存在");
            }
            else
            {
                var entity = new gw_goods_service()
                {
                    title = input.title,
                    content = input.content == null ? "" : input.content,
                    sort = input.sort,
                    remark = input.remark == null ? "" : input.remark,
                    add_time = DateTime.Now,
                    status = 1
                };
                db.gw_goods_services.Add(entity);
                var result = await db.SaveChangesAsync();
                if (result > 0)
                {
                    return ReturnSuccess<bool>(true);
                }
                else
                {
                    return ReturnError<bool>("保存失败，请重试！");
                }
            }
        }

        public IList<ServiceDto> GetAllServiceByPage(int iDisplayStart, int iDisplayLength, string title, int status, out int totalCount)
        {
            iDisplayLength = iDisplayLength < 1 ? 10 : iDisplayLength;
            var list = db.gw_goods_services
                .Select(item => new ServiceDto
                {
                    id = item.id,
                    title = item.title,
                    sort = item.sort,
                    content = item.content,
                    remark = item.remark,
                    status = item.status,
                    add_time = item.add_time
                });
            if (status > -1)
            {
                list = list.Where(m => m.status == status);
            }
            if (!string.IsNullOrWhiteSpace(title))
            {
                list = list.Where(m => m.title.Contains(title));
            }

            totalCount = list.Count();
            list = list.OrderByDescending(m => m.add_time).Skip(iDisplayStart).Take(iDisplayLength);
            return list.ToList();
        }

        public ServiceDto GetServiceById(int id)
        {
            var entity = db.gw_goods_services.FirstOrDefault(i => i.id == id);
            if (null != entity)
            {
                return new ServiceDto()
                {
                    id = entity.id,
                    title = entity.title,
                    sort = entity.sort,
                    status = entity.status,
                    content = entity.content,
                    remark = entity.remark,
                    add_time = entity.add_time
                };
            }
            else
            {
                return null;
            }
        }

        public bool IsExistService(string name)
        {
            return db.gw_goods_services.Any(i => i.title == name);
        }

        public bool SetIsServiceUse(int manageId, int id, int isUse)
        {
            LogHelper.WriteLog(String.Format("管理员{0}操作商品服务{1}状态为{2}", manageId, id, isUse));
            var entity = db.gw_goods_services.FirstOrDefault(i => i.id == id);
            if (null != entity)
            {
                entity.status = (byte)isUse;
                db.SaveChanges();
                return true;
            }
            return false;
        }
        #endregion

        #region 会员特权
        public async Task<Response<bool>> AddorEditUserRule(int managerId, UserRuleInput input)
        {
            //TODO:数据验证
            StringBuilder errorList = new StringBuilder();
            if (string.IsNullOrEmpty(input.title))
            {
                errorList.Append("特权名称不能为空；</br>");
            }
            if (string.IsNullOrEmpty(input.ico))
            {
                errorList.Append("请上传图标；</br>");
            }
            if (string.IsNullOrEmpty(input.selected_ico))
            {
                errorList.Append("请上传选中图标；</br>");
            }
            if (string.IsNullOrEmpty(input.picture_url))
            {
                errorList.Append("请上传特权介绍图；</br>");
            }
            if (!string.IsNullOrWhiteSpace(errorList.ToString()))
            {
                return ReturnError<bool>(errorList.ToString());
            }
            if (input.id > 0)
            {
                var entity = db.gw_user_rules.Include(i=>i.gw_user_rule_picture).FirstOrDefault(i => i.id == input.id);
                if (entity != null)
                {
                    entity.title = input.title;
                    entity.title_sub = input.title_sub == null ? "" : input.title_sub;
                    entity.ico = input.ico;
                    entity.selected_ico = input.selected_ico;
                    entity.picture_url = input.picture_url;
                    entity.subhead = input.subhead == null ? "" : input.subhead;
                    entity.summary = input.summary == null ? "" : input.summary;
                    entity.content = input.content == null ? "" : input.content;
                    entity.sort = input.sort;
                    //图片
                    var delList = entity.gw_user_rule_picture;
                    if (delList.Count() > 0)
                    {
                        db.gw_user_rule_pictures.RemoveRange(delList);
                    }
                    List<gw_user_rule_picture> info_add = new List<gw_user_rule_picture>();
                    var info_img_count = input.info_img_List == null ? 0 : input.info_img_List.Count();

                    if (info_img_count > 0)
                    {
                        for (int i = 0; i < info_img_count; i++)
                        {
                            gw_user_rule_picture imgModel = new gw_user_rule_picture();
                            imgModel.user_rule_id = entity.id;
                            imgModel.url = input.info_img_List[i];
                            imgModel.sort = i + 1;
                            info_add.Add(imgModel);
                        }
                    }
                    if (info_add.Count() > 0)
                    {
                        db.gw_user_rule_pictures.AddRange(info_add);
                    }
                    await db.SaveChangesAsync();
                    return ReturnSuccess<bool>(true);
                }
                return ReturnError<bool>("特权信息不存在");
            }
            else
            {
                var entity = new gw_user_rule()
                {
                    title = input.title,
                    title_sub = input.title_sub == null ? "" : input.title_sub,
                    ico = input.ico,
                    selected_ico = input.selected_ico,
                    picture_url = input.picture_url,
                    subhead = input.subhead == null ? "" : input.subhead,
                    summary = input.summary == null ? "" : input.summary,
                    content = input.content == null ? "" : input.content,
                    sort = input.sort,
                    add_time = DateTime.Now,
                    status = 1
                };
                var model = db.gw_user_rules.Add(entity);
                List<gw_user_rule_picture> info_add = new List<gw_user_rule_picture>();
                var info_img_count = input.info_img_List == null ? 0 : input.info_img_List.Count();

                if (info_img_count > 0)
                {
                    for (int i = 0; i < info_img_count; i++)
                    {
                        gw_user_rule_picture imgModel = new gw_user_rule_picture();
                        imgModel.user_rule_id = model.id;
                        imgModel.url = input.info_img_List[i];
                        imgModel.sort = i + 1;
                        info_add.Add(imgModel);
                    }
                }
                if (info_add.Count() > 0)
                {
                    db.gw_user_rule_pictures.AddRange(info_add);
                }
                var result = await db.SaveChangesAsync();
                if (result > 0)
                {
                    return ReturnSuccess<bool>(true);
                }
                else
                {
                    return ReturnError<bool>("保存失败，请重试！");
                }
            }
        }

        public IList<UserRuleDto> GetAllUserRuleByPage(int iDisplayStart, int iDisplayLength, string title, int status, out int totalCount)
        {
            iDisplayLength = iDisplayLength < 1 ? 10 : iDisplayLength;
            var list = db.gw_user_rules
                .Select(item => new UserRuleDto
                {
                    id = item.id,
                    title = item.title,
                    title_sub = item.title_sub,
                    sort = item.sort,
                    ico = item.ico,
                    subhead = item.subhead,
                    selected_ico = item.selected_ico,
                    //picture_url = item.picture_url,
                    status = item.status,
                    summary = item.summary,
                    add_time = item.add_time
                });
            if (status > -1)
            {
                list = list.Where(m => m.status == status);
            }
            if (!string.IsNullOrWhiteSpace(title))
            {
                list = list.Where(m => m.title.Contains(title));
            }

            totalCount = list.Count();
            list = list.OrderByDescending(m => m.add_time).Skip(iDisplayStart).Take(iDisplayLength);
            return list.ToList();
        }

        public UserRuleInput GetUserRuleById(int id)
        {
            var entity = db.gw_user_rules.Include(i=>i.gw_user_rule_picture).FirstOrDefault(i => i.id == id);
            if (null != entity)
            {
                var model= new UserRuleInput()
                {
                    id = entity.id,
                    title = entity.title,
                    title_sub = entity.title_sub,
                    subhead = entity.subhead,
                    ico = entity.ico,
                    selected_ico = entity.selected_ico,
                    picture_url = entity.picture_url,
                    summary = entity.summary,
                    content = entity.content,
                    sort = entity.sort,
                };
                model.info_img_List= new List<string>();
                if (entity.gw_user_rule_picture!=null)
                {
                    foreach (var item in entity.gw_user_rule_picture)
                    {
                        model.info_img_List.Add(item.url);
                    }
                }
                return model;
            }
            else
            {
                return null;
            }
        }

        public List<UserRuleImgDto> GetUserRulePictures(int rId)
        {
            var list = db.gw_user_rule_pictures
                .Where(i => i.user_rule_id == rId)
                .OrderBy(i => i.sort)
                .Select(item => new UserRuleImgDto
                {
                    id = item.id,
                    url = item.url,
                    sort = item.sort
                });
            return list.ToList();
        }

        public bool IsExistUserRule(string name)
        {
            return db.gw_user_rules.Any(i => i.title == name);
        }

        public bool SetIsUserRuleUse(int manageId, int id, int isUse)
        {
            LogHelper.WriteLog(String.Format("管理员{0}操作会员特权{1}状态为{2}", manageId, id, isUse));
            var entity = db.gw_user_rules.FirstOrDefault(i => i.id == id);
            if (null != entity)
            {
                entity.status = (byte)isUse;
                db.SaveChanges();
                return true;
            }
            return false;
        } 
        #endregion
    }
}
